package net.zoneland.knowledge.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.util.StringUtils;
import net.zoneland.knowledge.service.EsService;
import net.zoneland.knowledge.utils.LoggerHelper;

/**
 * 维护数据controller.
 *
 * @author: bcc
 * 2021/11/16
 */
@RestController
@RequestMapping("/datahelper")
public class DataHelperController {
    /**
     * 日志.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(DataHelperController.class);
    /**
     * 授权用户.
     */
    private static final String ALLOWED_USER = "cjfz";

    @Autowired
    private EsService esService;
    
    /**
     * 用于维护查询ES数据.
     * @param request http请求
     * @param jsonStr json字符串
     * @param endPoint es请求路径
     * @param method  http方法
     * @return rst
     * @throws Exception 异常
     */
    @PostMapping(value = "/maintain.ajax", produces = "application/json;charset=UTF-8")
    public String maintain(final HttpServletRequest request,
                           @RequestParam("jsonStr")final String jsonStr,
                           @RequestParam("endPoint")final String endPoint,
                           @RequestParam("method")final String method) throws Exception {
        // Logging should not be vulnerable to injection attacks
        LOGGER.info("jsonStr:{},endPoint:{},method:{}",
                LoggerHelper.replaceBreakCharacters(jsonStr),
                LoggerHelper.replaceBreakCharacters(endPoint),
                LoggerHelper.replaceBreakCharacters(method));

        if (!StringUtils.equals(request.getRemoteUser(), ALLOWED_USER)) {
            return "请求非法";
        }

        return esService.maintain(jsonStr, endPoint, method);
    }

}
